#include "Vector.h"
// reallocate()
// 下面代码来自<c++ primer>第四版 18.1.2 allocator类

template <class T, class Alloc>
void Vector<T, Alloc>::reallocate()
{
	difference_type size = first_free - elements;
	difference_type newcapacity = 2 * max(size, 1);
	
	pointer newelements = alloc.allocate(newcapacity);
	alloc.uninitialized_copy(elements, first_free, newelements);
	for (pointer p = first_free; p != elements; /* empty */)
		alloc.destroy(--p);

	if (elements)
		alloc.deallocate(elements, tail - elements);
	elements = newelements;
	first_free = elements + size;
	tail = elements + newcapacity;	
}


template <class T, class Alloc> template <class InputIterator> 
void Vector<T, Alloc>::assign (InputIterator first, InputIterator last)
{
	difference_type size = last - first;
	difference_type capacity = tail - elements;

	if (size > capacity) {
		difference_type newcapacity = 2 * max(size, 1);
		for (pointer p = first_free; p != elements; /* empty */)
			alloc.destroy(--p);
		if (elements)
			alloc.deallocate(elements, tail - elements);
		elements = alloc.allocate(newcapacity);
		tail = elements + newcapacity;	
	}

	alloc.uninitialized_copy(first, last, elements);

	first_free = elements + size;
}

template<class T, class Alloc>
void Vector<T, Alloc>::assign (size_type n, const T& u)
{
	difference_type capacity = tail - elements;

	if (n > capacity) {
		difference_type newcapacity = 2 * max(n, 1);
		for (pointer p = first_free; p != elements; /* empty */)
			alloc.destroy(--p);
		if (elements)
			alloc.deallocate(elements, tail - elements);
		elements = alloc.allocate(newcapacity);
		tail = elements + newcapacity;	
	}

	alloc.uninitialized_fill(elements, elements + n, u);

	first_free = elements + n;
}


